package biznussoft.metercor.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import biznussoft.metercor.MainActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.entity.ActivityModel;
import biznussoft.metercor.entity.MaterialModel;
import biznussoft.metercor.lookup.ItemIdLookUp;
import biznussoft.metercor.utils.CustomProgressDialog;
import biznussoft.metercor.utils.ExpandCollapseAnimation;
import biznussoft.metercor.utils.Session;

import com.google.gson.Gson;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class MaterialMasterFragment extends Fragment implements OnTouchListener, OnClickListener{
	
	private int mHeight2 = 0;
	private LinearLayout materialLayout,newMaterialLayout;
	public static RelativeLayout layout;
	private RestClient client;
	private ActivityModel mobel;
	private String strId;
	private ImageView material,save;
	private Dialog progressDialog;
	private Spinner spAction;
	private CheckBox cbEditBillable;
	private int position;
	private EditText etQuantity,etDiscount;
	public static EditText etItemId;
	public static boolean flag;
	public static ArrayList<MaterialModel> materialList;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.material_master_fragment, null);
	}
	


	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		client = MainActivity.mActivity.client;
		material = (ImageView) getView().findViewById(R.id.addMaterial);
		materialLayout = (LinearLayout) getView().findViewById(R.id.sectionsLayout2);
		newMaterialLayout = (LinearLayout) getView().findViewById(R.id.lllayout_material_newmode);
		etItemId = (EditText) getView().findViewById(R.id.etItemId);
		spAction = (Spinner) getView().findViewById(R.id.spAction);
		etQuantity = (EditText) getView().findViewById(R.id.etQuantity);
		etDiscount = (EditText) getView().findViewById(R.id.etDiscount);
		cbEditBillable = (CheckBox) getView().findViewById(R.id.cbeditBillable);
		save = (ImageView) getView().findViewById(R.id.save);
		layout = (RelativeLayout) getView().findViewById(R.id.rr_layout);
		etItemId.setOnTouchListener(this);
		save.setOnClickListener(this);
		
		Bundle i = getArguments();
		progressDialog = CustomProgressDialog.getInstance().createProgressDialog(getActivity());
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.show();
		position = i.getInt("Position");
		getDetails(position);
		
		material.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				addNewMaterial();				
			}
		});
	}

	
	public void addNewMaterial() {
		// TODO Auto-generated method stub
		materialLayout.setVisibility(View.GONE);
		newMaterialLayout.setVisibility(View.VISIBLE);
	}

	
	
	
	public void  getDetails(int position){

		mobel = ServiceOrderActivityRecordsFragment.list.get(position);
		Session.sFconnectActivity =mobel.getActivityName();
		strId = mobel.getId();
		getMaterial(strId);


	}
	
	public void getMaterial(String id){


		try{

			String serviceOrder = "SELECT Item_Name__c,FConnect__Total_Price1__c,Name,Id,Activity_Name__c,FConnect__Technician__c,FConnect__Action__c,FConnect__Quantity__c,FConnect__Billable__c,FConnect__Discount_Amount__c,FConnect__Discription__c,FConnect__Failure_Code__c,FConnect__Failure_Code_Discription__c,FConnect__Item__c,FConnect__Inventory_ID__c,FConnect__Serial_ID__c,FConnect__Exchange__c,FConnect__Lot_ID__c From FConnect__Material__c WHERE FConnect__Activity__c="+"'"+id+"'";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), serviceOrder);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {  
						progressDialog.dismiss();
						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						materialList = new ArrayList<MaterialModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								MaterialModel bean = _gson.fromJson(jsonArray.getString(i), MaterialModel.class);
								materialList.add(bean);
							}
						}

						showRecords();

					} catch (Exception e) {

						Log.i("NCS","Exception is  :"+e.getMessage());
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  material  is  :"+e.getMessage());
		}



	}
	
	public void showRecords(){


		for (int i = 0; i < materialList.size(); i++) {

			MaterialModel donor = materialList.get(i);
			View view = getActivity().getLayoutInflater().inflate(R.layout.material_displaydata, materialLayout,false);

			//View headerColor = (View)view.findViewById(R.id.title_graphic);
			//headerColor.setBackgroundResource(R.drawable.title_bar_orange);

			TextView	mName = (TextView) view.findViewById(R.id.tvContactLastName);
			TextView	mAction = (TextView) view.findViewById(R.id.tvContactTitle);
			TextView 	mQuantity= (TextView) view.findViewById(R.id.tvContactEmail);
			TextView 	mNetPay = (TextView) view.findViewById(R.id.tvContactPhone);

			mName.setText(donor.getName());
			mAction.setText(donor.getAction());
			mQuantity.setText(donor.getQuantity());
			mNetPay.setText(donor.getNetPay());

			materialLayout.addView(view);


			final ImageView iv_expandcollapse = (ImageView) view.findViewById(R.id.iv_CollapseExpand);
			final LinearLayout sectionitemsParent = (LinearLayout) view.findViewById(R.id.llSectionItems);
			iv_expandcollapse.setImageResource(R.drawable.expand);
			sectionitemsParent.setVisibility(View.GONE);


			iv_expandcollapse.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

					if (sectionitemsParent.getVisibility() == View.VISIBLE) {// Collapse
						ExpandCollapseAnimation collapseAnimation = new ExpandCollapseAnimation(sectionitemsParent, 1000, 1, iv_expandcollapse);
						mHeight2 = collapseAnimation.getHeight();
						iv_expandcollapse.startAnimation(collapseAnimation);
					} else {// Expand
						ExpandCollapseAnimation expandAnimation = new ExpandCollapseAnimation(sectionitemsParent, 1000, 0, iv_expandcollapse);
						if (mHeight2 == 0) {
							mHeight2 = getSectionitemsHeight();
						}
						expandAnimation.setHeight(mHeight2);
						iv_expandcollapse.startAnimation(expandAnimation);
					}
				}

				private int getSectionitemsHeight() {
					return (int) (4 * getResources().getDimension(R.dimen.section_item_height));
				}
			});
		}




	
	}



	@Override
	public boolean onTouch(View v, MotionEvent event) {
		
		switch (v.getId()) {
		
		case R.id.etItemId:
			if(event.getAction() ==MotionEvent.ACTION_UP){
			ItemIdLookUp lookup = new ItemIdLookUp();
			lookup.getItemLookUp(getActivity(),"Material");}
			
			break;

		default:
			break;
		}
		return false;
	}



	@Override
	public void onClick(View arg0) {
		
		boolean billable =  cbEditBillable.isChecked();
		String objectType = "FConnect__Material__c";             
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("FConnect__Activity__c",strId);                  
		fields.put("FConnect__Technician__c",Session.sTechnicianId);
		fields.put("FConnect__Action__c",spAction.getSelectedItem().toString());
		fields.put("FConnect__Inventory_ID__c",Session.sItemId); 
		fields.put("FConnect__Site__c",Session.sTechnicianSiteId);
		fields.put("FConnect__Discount__c",etDiscount.getText().toString());
		fields.put("FConnect__Billable__c",billable);
		if(!flag)
		fields.put("FConnect__Quantity__c",1);
		else
		fields.put("FConnect__Quantity__c",etQuantity.getText().toString());
	
		
		
		try {                             
			RestRequest restRequest = RestRequest.getRequestForCreate(getString(R.string.api_version),objectType,fields);
		    
		    client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {  
						MaterialMasterFragment newFragment2 = new MaterialMasterFragment();
						Bundle args2 = new Bundle();
						args2.putInt("Position", position);
						newFragment2.setArguments(args2);
						FragmentTransaction transaction2 = getActivity().getSupportFragmentManager().beginTransaction();
						transaction2.replace(R.id.menus, newFragment2);                 
						transaction2.commit();
						}                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}
				
				//@Override
				public void onError(Exception exception) {
					 
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());
		}

	
	}

}
